<template>
    <div>
        <div style="display: flex; justify-content: space-between;margin-bottom:10px;">
            <div style="display: flex; justify-content: flex-start; width: 45%">
                <a-button @click="addData">新增</a-button>
                <a-button @click="importPenaltyPriceData" style="margin-left:10px;">引入</a-button>
                <a-button @click="deleteData" style="margin-left:10px;">删除</a-button>  
            </div>
           
            <div style="display: flex; justify-content: flex-end; width: 55%">
                <span style="margin-right:30px;">扣罚金额合计: {{ totalAmount }} 元</span>
            </div>

        </div>
        <a-form-model ref="penaltyClauseList">
            <a-table :columns="columns" :data-source="records" 
            :pagination="false" :rowKey="(record, index) => { return index }" 
            bordered :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

            <template slot="sortIndexRender" slot-scope="text, record, index">
                {{ index + 1 }}
            </template>

            <span slot="penaltySourceDocumentRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-select style="width: 100%" v-model="record.sourceDocument" :disabled="record.disabled"
                        :options="sourceDocumentDict.map(item => ({ value: item.code,label: item.name }))">
                    </a-select>
                </a-form-model-item>
            </span>
            
            <span slot="penaltyCodeRender" slot-scope="text, record">
                <a-form-model-item>
                    {{ record.penaltyCode }}
                    <!--<a-input style="width: 100%" v-model="record.penaltyCode"></a-input>-->
                </a-form-model-item>
            </span>

            <span slot="penaltyNameRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.penaltyName" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>
            
            <span slot="penaltyPatternRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-select style="width: 100%" v-model="record.penaltyPattern" :disabled="record.disabled" 
                        :options="penaltyPatternDict.map(item => ({ value: item.code,label: item.name }))">
                    </a-select>
                </a-form-model-item>
            </span>

            <span slot="penaltyUnitRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-select style="width: 100%" v-model="record.penaltyUnit"  :disabled="record.disabled"
                        :options="penaltyUnitDict.map(item => ({ value: item.code,label: item.name }))">
                    </a-select>
                </a-form-model-item>
            </span>

            <span slot="penaltyPriceMinRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.penaltyPriceMin" type="number" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>

            <span slot="penaltyPriceMaxRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.penaltyPriceMax" type="number" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>
            
            <span slot="baseSourceRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.baseSource" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>

            <span slot="penaltyPerMinRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.penaltyPerMin" type="number" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>

            <span slot="penaltyPerMaxRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.penaltyPerMax" type="number" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>

            <span slot="thisTimePenaltyNumRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.thisTimePenaltyNum" type="number" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>

            <span slot="thisTimePenaltyAmountRender" slot-scope="text, record">
                <a-form-model-item>
                    <a-input style="width: 100%" v-model="record.thisTimePenaltyAmount" type="number" @change="e => inputAmountValue(e.target.value)" :disabled="record.disabled"></a-input>
                </a-form-model-item>
            </span>

            </a-table>
        </a-form-model>


        <!-- 引入按钮(mdm工程扣罚价格数据) 弹框内容 -->
        <div>
            <a-modal v-model:visible="gcPenaltyPriceVisible" title="工程扣罚价格数据" width="1600px" style="margin-right:200px;" @ok="submitMdmData">
                <!-- 搜索条件 -->
                <a-form layout="inline">
                    <a-form-item label="扣罚编码">
                        <a-input :value="listQuery.penaltyCode" style="width:200px;"/>
                    </a-form-item>

                    <a-form-item label="扣罚名称">
                        <a-input :value="listQuery.penaltyName" style="width:200px;"/>
                    </a-form-item>

                    <a-button type="primary" @click="doSearch">搜索</a-button>

                </a-form>

                <!-- 表格数据 -->
                <a-table :columns="gcPenaltyPriceColumns" :data-source="gcPenaltyPriceRecords" bordered style="width:1500px;"
                :pagination="false" :rowKey="(record, index) => { return index }" 
                :row-selection="{ selectedRowKeys: gcPenaltyPriceSelectedRowKeys, onChange: gcPenaltyPriceOnSelectChange }">
                
                <template slot="mdmSortIndexRender" slot-scope="text, record, index">
                    {{ index + 1 }}
                </template>

                <span slot="mdmSourceDocument" slot-scope="text, record">
                    {{ transferDictValue('gc_source_document',record.sourceDocument) }}
                </span>

                <span slot="mdmPenaltyPattern" slot-scope="text, record">
                    {{ transferDictValue('gc_penalty_pattern',record.penaltyPattern) }}
                </span>

                <span slot="mdmPenaltyUnit" slot-scope="text, record">
                    {{ transferDictValue('gc_penalty_unit',record.penaltyUnit) }}
                </span>

                <span slot="mdmContractCategory" slot-scope="text, record">
                    {{ transferDictValue('contract_category',record.contractCategory) }}
                </span>
                </a-table>
                <!-- 分页 -->
                <a-pagination :current="listQuery.pageNo" :page-size="listQuery.pageSize" :total="totalGcPenaltyPriceRecords"  style="margin-top:15px;"/>
            </a-modal>
        </div>

    </div>
</template>


<script>
import { getAction, postAction } from '@/api/manage'
import { resolve } from 'path'

export default {
    props:{
        qualityId: {
            type: String,
            default: null,
        },
        contractNo: {
            type: String,
            default: null,
        },
        showPenaltyClauseSection:{
            type: Boolean,
            default:false
        }
    },


    mounted() {
        console.log('this.qualityId:',this.qualityId)
        console.log('this.contractNo:',this.contractNo)
        console.log('init data...')
        this.initData()
    },
    data() {
       return {
            urls: {
             list: '/qualityContractPenaltyClause/list',
             dictList:'/mdmDict/queryByModel',
             gcPenaltyPriceList:'/mdmGcPenaltyPrice/list',
             generatePenaltyCode:'/qualityContractPenaltyClause/generatePenaltyCode'
            },
            columns:[
                {
                    title: '序号',
                    dataIndex: 'sortIndex',
                    scopedSlots: { customRender: 'sortIndexRender' },
                    width: '80px',
                    align: 'center',
                },
                {
                    title: '信息来源    ',
                    dataIndex: 'sourceDocument',
                    key: 'sourceDocument',
                    scopedSlots: { customRender: 'penaltySourceDocumentRender' },
                    align: 'center',
                    width: '120px',
                },

                {
                    title: '扣罚编码',
                    dataIndex: 'penaltyCode',
                    key: 'penaltyCode',
                    scopedSlots: { customRender: 'penaltyCodeRender' },
                    width: '120px',
                },
                {
                    title: '扣罚名称',
                    dataIndex: 'penaltyName',
                    key: 'penaltyName',
                    scopedSlots: { customRender: 'penaltyNameRender' },
                },
                {
                    title: '扣罚模式',
                    dataIndex: 'penaltyPattern',
                    key: 'penaltyPattern',
                    scopedSlots: { customRender: 'penaltyPatternRender' },
                    width: '120px',
                },
                {
                    title: '扣罚单位',
                    dataIndex: 'penaltyUnit',
                    key: 'penaltyUnit',
                    scopedSlots: { customRender: 'penaltyUnitRender' },
                    width: '120px',
                },
                {
                    title: '扣罚单价下限',
                    dataIndex: 'penaltyPriceMin',
                    key: 'penaltyPriceMin',
                    scopedSlots: { customRender: 'penaltyPriceMinRender' },
                },
                {
                    title: '扣罚单价上限',
                    dataIndex: 'penaltyPriceMax',
                    key: 'penaltyPriceMax',
                    scopedSlots: { customRender: 'penaltyPriceMaxRender' },
                },
                {
                    title: '基数依据',
                    dataIndex: 'baseSource',
                    key: 'baseSource',
                    scopedSlots: { customRender: 'baseSourceRender' },
                },
                {
                    title: '扣罚百分比下限参考',
                    dataIndex: 'penaltyPerMin',
                    key: 'penaltyPerMin',
                    scopedSlots: { customRender: 'penaltyPerMinRender' },
                },
                {
                    title: '总扣罚百分比上限参考',
                    dataIndex: 'penaltyPerMax',
                    key: 'penaltyPerMax',
                    scopedSlots: { customRender: 'penaltyPerMaxRender' },
                },
                {
                    title: '本次扣罚数量',
                    dataIndex: 'thisTimePenaltyNum',
                    key: 'thisTimePenaltyNum',
                    scopedSlots: { customRender: 'thisTimePenaltyNumRender' },
                    width: '80px',
                },
                {
                    title: '本次扣罚金额',
                    dataIndex: 'thisTimePenaltyAmount',
                    key: 'thisTimePenaltyAmount',
                    scopedSlots: { customRender: 'thisTimePenaltyAmountRender' },
                    width: '80px',
                },
            ],
            latestPenaltyCode:'',
            totalAmount:0,  //总金额
            records:[],  //合同扣罚条款数据
            sourceDocumentDict:[],
            penaltyPatternDict:[],
            penaltyUnitDict:[],
            contractCategoryDict:[],
            //sourceDocumentDict:[{code:'10',name:'GC10 建筑钢结构工程制作安装合同'},{code:'11',name:'GC11 建设工程监理合同'}],
            //penaltyPatternDict:[{code:'1',name:'按人数扣罚'},{code:'2',name:'按次扣罚'},{code:'10',name:'按范围扣罚'},{code:'11',name:'按百分比扣罚'}],
            //penaltyUnitDict:[{code:'1',name:'元/人'},{code:'2',name:'元/次'}],
            //contractCategoryDict:[{code:'CC',name:'CC 仓储类合同'},{code:'CG',name:'CG 设备采购类合同'},{code:'GC',name:'GC 工程类合同'}],
            //penaltySourceDocumentDict:[{code:'1',name:''}],
            currentSelection: [],
            selectedRowKeys: [],
            deleteRecords:[],

            //mdm列表数据相关
            gcPenaltyPriceVisible:false,
            listQuery:{pageNo:1,pageSize:10,penaltyCode:'',penaltyName:''},
            totalGcPenaltyPriceRecords:0,
            gcPenaltyPriceSelectedRowKeys:[],
            gcPenaltyPriceCurrentSelection:[],
            gcPenaltyPriceRecords:[],
            gcPenaltyPriceColumns:[
                {
                title: '序号',
                dataIndex: 'sortIndex',
                scopedSlots: { customRender: 'mdmSortIndexRender' },
                width: '80px',
                align: 'center',
                },
                
                {
                    title: '信息来源    ',
                    dataIndex: 'sourceDocument',
                    key: 'sourceDocument',
                    scopedSlots: { customRender: 'mdmSourceDocument' }
                },
                {
                    title: '扣罚编码',
                    dataIndex: 'penaltyCode',
                    key: 'penaltyCode',
                },
                {
                    title: '扣罚名称',
                    dataIndex: 'penaltyName',
                    key: 'penaltyName',
                },
                {
                    title: '扣罚模式',
                    dataIndex: 'penaltyPattern',
                    key: 'penaltyPattern',
                    scopedSlots: { customRender: 'mdmPenaltyPattern' }
                },
                {
                    title: '扣罚单位',
                    dataIndex: 'penaltyUnit',
                    key: 'penaltyUnit',
                    scopedSlots: { customRender: 'mdmPenaltyUnit' }
                },
                {
                    title: '扣罚单价下限',
                    dataIndex: 'penaltyPriceMin',
                    key: 'penaltyPriceMin',
                },
                {
                    title: '扣罚单价上限',
                    dataIndex: 'penaltyPriceMax',
                    key: 'penaltyPriceMax',
                },
                {
                    title: '基数依据',
                    dataIndex: 'baseSource',
                    key: 'baseSource',
                },
                {
                    title: '扣罚百分比下限参考',
                    dataIndex: 'penaltyPerMin',
                    key: 'penaltyPerMin',
                },
                {
                    title: '总扣罚百分比上限参考',
                    dataIndex: 'penaltyPerMax',
                    key: 'penaltyPerMax',
                },
                {
                    title: '合同类别',
                    dataIndex: 'contractCategory',
                    key: 'contractCategory',
                    scopedSlots: { customRender: 'mdmContractCategory' }
                },
                {
                    title: '合同编号',
                    dataIndex: 'contractCode',
                    key: 'contractCode',
                },
            ]
       }
    },
    
    methods: { 
        initData(){
            //初始化字典值
            this.getDict('gc_source_document')
            this.getDict('gc_penalty_pattern')
            this.getDict('gc_penalty_unit')
            this.getDict('contract_category')
            //初始化合同扣罚条款列表
            this.getlist()
        },
        
        //获取字典在方法
        getDict(modelName){
            let list = []
            let url = this.urls.dictList
            let reqData = {model:modelName}
            postAction(url,reqData).then((res)=>{
                //console.log('字典:',JSON.stringify(res))
                if(res.code === 200){
                    list = res.result
                    //console.log('list:',JSON.stringify(list))
                    if(modelName == 'gc_source_document'){
                        this.sourceDocumentDict = list
                        //console.log('sourceDocumentDict:',this.sourceDocumentDict)
                    }else if(modelName == 'gc_penalty_pattern'){
                        this.penaltyPatternDict = list
                        //console.log('penaltyPatternDict:',this.penaltyPatternDict)
                    }else if(modelName == 'gc_penalty_unit'){
                        this.penaltyUnitDict = list
                        //console.log('penaltyUnitDict',this.penaltyUnitDict)
                    }else if(modelName == 'contract_category'){
                        this.contractCategoryDict = list
                        //console.log('contractCategoryDict:',this.contractCategoryDict)
                    }
                }
            })
            

            

        },
        //获取合同扣罚条款的方法
        getlist(){
            this.records = []
            if(this.qualityId){
              let id = this.qualityId
              let url = this.urls.list + '/' + id
              getAction(url).then((res)=>{
                console.log('res:',JSON.stringify(res))
                if(res.code === 200){
                    this.records = res.result
                    if(this.records && this.records.length > 0){
                        this.records.forEach(item =>{
                            if(item.penaltyCode.substr(0,2) != 'HX'){
                                //禁止修改
                                item.disabled = true
                            }
                        })
                    }
                    this.caculateAmount()
                }
              })
            }
        },

        emptyDelData(){
            this.deleteRecords = []
        },
        //获取数据列表
        getDataList(){
            return this.records
        },

        getDelDataList(){
            return this.deleteRecords
        },

       addData(){
        console.log('新增')
            this.getLatestPenaltyCodeInfo();
        },
        importPenaltyPriceData(){
            console.log('引入')
            this.gcPenaltyPriceVisible = true
            this.getGcPenaltyPriceList()
        },
        deleteData(){
            // console.log('删除')
            // console.log('删除 this.selectedRowKeys ',this.selectedRowKeys);
            // console.log('删除 this.currentSelection ',this.currentSelection);
            let startIndex = 0
            let newRecords = []
             //console.log(this.records)
            let deleteIndexArr = []
            for(let item of this.records){
                console.log(item)
               
                let flag = this.selectedRowKeys.includes(startIndex)
                console.log('current flag',flag)
                if(this.selectedRowKeys.includes(startIndex)){
                    //this.records.splice(startIndex,1);
                    deleteIndexArr.push(startIndex)
                    //要更新状态的item
                    if(item.id){
                        item.isDel = 1
                        this.deleteRecords.push(item)
                    }
                }
                startIndex = startIndex + 1
            }
            console.log('deleteIndexArr:',deleteIndexArr)
            this.records.map((item,index)=>{
                if(!deleteIndexArr.includes(index)){
                    newRecords.push(item)
                }
            }) 
            console.log(newRecords)
            this.records = newRecords
            this.selectedRowKeys = []
            this.currentSelection = []
            this.caculateAmount() //计算金额
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            console.log(selectedRowKeys)
            console.log(selectedRows)
            this.selectedRowKeys = selectedRowKeys
            this.currentSelection = selectedRows
        },

        getGcPenaltyPriceList(){
            //let listQuery = {page:1,pageSize:10}
            let url = this.urls.gcPenaltyPriceList
            console.log('this.contractNo:',this.contractNo)
            this.$set(this.listQuery, 'contractCode', this.contractNo || '')
            postAction(url,this.listQuery).then((res)=>{
                //console.log('获取mdm数据:',JSON.stringify(res))
                if(res.code === 200){
                    console.log(res.result.total)
                    this.gcPenaltyPriceRecords = res.result.records
                    this.totalGcPenaltyPriceRecords = res.result.total
                }
            })
        },
        gcPenaltyPriceOnSelectChange(selectedRowKeys, selectedRows){
            console.log(selectedRowKeys)
            console.log(selectedRows)
            this.gcPenaltyPriceSelectedRowKeys = selectedRowKeys
            this.gcPenaltyPriceCurrentSelection = selectedRows
        },
        submitMdmData(){
            this.gcPenaltyPriceVisible = false
            console.log('点击确定')
            if(this.gcPenaltyPriceCurrentSelection && this.gcPenaltyPriceCurrentSelection.length > 0){
                for(let item of this.gcPenaltyPriceCurrentSelection){
                    item.qualityId = this.qualityId
                    item.disabled = true
                    this.records.push(item)
                }
            }
            //重置条件
            this.listQuery = {pageNo:1,pageSize:10,penaltyCode:'',penaltyName:'',contractCode:this.contractNo}
            this.gcPenaltyPriceSelectedRowKeys = []
            this.gcPenaltyPriceCurrentSelection = []
        },

        //计算总金额
        caculateAmount(){
            console.log('计算总金额:',this.records)
            let amount = 0
            //console.log('计算总金额:',this.records)
            if(this.records && this.records.length > 0){
                    for(let item of this.records){
                    if(item.thisTimePenaltyAmount && item.thisTimePenaltyAmount > 0){
                        console.log('当前金额:',item.thisTimePenaltyAmount)
                        amount = Math.floor(parseFloat((amount + parseFloat(item.thisTimePenaltyAmount)) *  100))/100
                    }
                }
                console.log('总金额:',amount)
                this.totalAmount = amount
            }
        },
        //监听金额输入框,计算总金额
        inputAmountValue(val){
            console.log('new val:',val)
            this.caculateAmount()
        },
        doSearch(){
          console.log('点击搜索 查询mdm数据')  
          this.getGcPenaltyPriceList()
        },
        //获取最新海芯的扣罚编码方法
        getLatestPenaltyCodeInfo(){    
            let url = this.urls.generatePenaltyCode
            getAction(url).then((res)=>{
                //console.log('获取mdm数据:',JSON.stringify(res))
                if(res.code === 200){
                    console.log(JSON.stringify(res))
                     let penaltyCode = res.result
                    this.pushItemToList(penaltyCode)
                }
            })
        },


        pushItemToList(penaltyCode){
            let item = {
                qualityId:this.qualityId,
                contractCode:this.contractNo,
                sourceDocument:'',
                penaltyCode: penaltyCode,
                penaltyName:'',
                penaltyPattern:'',
                penaltyUnit:'',
                penaltyPriceMin:'',
                penaltyPriceMax:'',
                baseSource:'',
                penaltyPerMin:'',
                penaltyPerMax:'',
                thisTimePenaltyNum:0,
                thisTimePenaltyAmount:0,
                isDel:0,
            }
            console.log(JSON.stringify(item))
            this.records.push(item)
        },

        //转换字典值方法
        transferDictValue(dictModel,code){
            //console.log('code:',code)
            //console.log('dictModel',dictModel)
            let dictArr = []
            if(dictModel == 'gc_source_document'){
                dictArr = this.sourceDocumentDict
            }else if(dictModel == 'gc_penalty_pattern'){
                dictArr = this.penaltyPatternDict
            }else if(dictModel == 'gc_penalty_unit'){
                dictArr = this.penaltyUnitDict
            }else if(dictModel == 'contract_category'){
                dictArr = this.contractCategoryDict
            }
            if(dictArr && dictArr.length > 0){
                for(let item of dictArr){
                    console.log('item',JSON.stringify(item))
                    if(item.code == String(code)){
                        //console.log('item.name:',item.name)
                        return item.name
                    }
                }
            }
            return code
        }
    },
    watch:{
        // qualityId(newV, old) {
        // if (newV) {
        //     this.getlist()
        // }
        // },
    }
}

</script>


<style scoped>
/deep/ .upload-demo {
  display: inline-block;
}
/deep/.ant-col .ant-form-item-label {
  min-width: 135px;
  line-height: 40px;
  display: inline-block;
  overflow: hidden;
  line-height: 39.9999px;
  white-space: nowrap;
  text-align: right;
  vertical-align: middle;
}
/deep/.ant-row .ant-form-item {
  display: flex;
}
/deep/.ant-col .ant-form-item-control-wrapper {
  width: 100%;
}
/deep/.anticon .anticon-plus-circle {
  display: flex;
  align-items: center;
}
/deep/.ant-calendar-picker {
  width: 100%;
}
.btn-box {
  margin-bottom: 15px;
}
.btn-box .ant-btn {
  margin-right: 10px;
}
/deep/.ant-form .ant-form-item-control-wrapper {
  display: inline-block;
  width: 100% !important;
}
>>> .ant-form .ant-form-item-control-wrapper {
  display: inline-block;
  width: 100% !important;
}
::v-deep.ant-form .ant-form-item-control-wrapper {
  display: inline-block;
  width: 100% !important;
}
/deep/.ant-form-item-control-wrapper {
  display: inline-block;
  width: 100% !important;
}
>>> .ant-form-item-control-wrapper {
  display: inline-block;
  width: 100% !important;
}
::v-deep.ant-form-item-control-wrapper {
  display: inline-block;
  width: 100% !important;
}
</style>